package com.tledu.httpclient;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * post 表单提交
 */
public class HttpClient03 {
    public static void main(String[] args) throws IOException {
        // 这是我写的一个接口，这个接口请求方式post ，传参方式 表单
        String url = "http://59.111.104.209:13000/form";
        // 1. 创建httpclient
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 2. 创建post请求
        HttpPost httpPost = new HttpPost(url);
        // 3. 封装参数
        List<NameValuePair> nameValuePairList = new ArrayList<>();
        nameValuePairList.add(new BasicNameValuePair("name","尚云科技"));
        // 4. 构建请求体（表单的请求题） 不同的请求题对应的请求头是不同Content-Type
        // 这种表单对应的请求头就是，application/x-www-form-urlencoded
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList,"utf-8");
        // 5. 设置请求体
        httpPost.setEntity(formEntity);
        // 6. 发送请求
        CloseableHttpResponse response = httpClient.execute(httpPost);
        // 7. 判断状态码
        int status = response.getStatusLine().getStatusCode();
        if (status != 200) {
            httpPost.abort();
            System.out.println("请求失败,当前的状态码为:"+status);
        }else {
            HttpEntity entity = response.getEntity();
            // 8. 获取请求结果
            System.out.println(EntityUtils.toString(entity));
            // 9. 关闭响应
            EntityUtils.consume(entity);
            response.close();
        }
    }
}
